package baiqitun.stupro.subject.util;

import baiqitun.stupro.common.exception.enums.support.StuproExceptionEnum;
import baiqitun.stupro.common.exception.enums.support.ExistedExceptionEnum;
import baiqitun.stupro.common.exception.support.ExistedException;
import baiqitun.stupro.common.exception.StuproException;
import baiqitun.stupro.security.entity.SysDepartUser;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysDepartUserService;
import baiqitun.stupro.security.service.SysUserService;
import baiqitun.stupro.security.util.AbstractUserInfoSaver;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Excel批量保存学生信息
 * @author kedaji
 */
@Service("studentInfoSaver")
public class StudentInfoSaver extends AbstractUserInfoSaver {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDepartUserService sysDepartUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void save(Map<String, Object> row, String createBy, String departId) {
        String username = (String)row.get("学号");
        if (username == null){
            throw new StuproException(StuproExceptionEnum.PARAMETER_CANNOT_NULL).put("学号",null);
        }
        SysUser resultUser = sysUserService.getUserByUsername(username);
        if (resultUser != null){
            throw new ExistedException(ExistedExceptionEnum.USER_EXISTED).put("学号", username);
        }
        String idNumber = ((String)row.get("身份证号"));
        String password = idNumber.substring(idNumber.length() - 5, idNumber.length() - 1);
        String encodedPassword = passwordEncoder.encode(DigestUtil.md5Hex(password));
        String realName = (String) row.get("姓名");
        SysUser user = new SysUser();
        user.setUsername(username).setPassword(encodedPassword).setRealName(realName).setCreateBy(createBy);
        sysUserService.save(user);
        SysDepartUser relation = new SysDepartUser();
        relation.setUserId(user.getId()).setDepartId(departId).setCreateBy(createBy);
        sysDepartUserService.save(relation);
    }
}
